import dayjs from 'dayjs'

export const formatDatetime = (datetime, format) => {
  return datetime ? dayjs(datetime).format(format) : ''
}

/**
 * 判断 select 是否早于 current
 * @param {string} select - 格式 "YYYY-M"
 * @param {string} current - 格式 "YYYY-M"
 * @returns {boolean} - 如果 select < current，返回 true；否则 false
 */
export const isBeforeMonth = (select, current) => {
  const parseToYearMonth = (input) => {
    if (!input) return null

    // 1. Date对象或字符串可转Date
    if (
      input instanceof Date ||
      !isNaN(Date.parse(input))
    ) {
      const d = new Date(input)
      return {
        year: d.getFullYear(),
        month: d.getMonth() + 1
      }
    }

    // 2. 字符串格式如 '2025-6'
    const matched = /^(\d{4})-(\d{1,2})$/.exec(input)
    if (matched) {
      return {
        year: Number(matched[1]),
        month: Number(matched[2])
      }
    }

    return null // 无法解析
  }

  const s = parseToYearMonth(select)
  const c = parseToYearMonth(current)

  if (!s || !c) return false // 无效格式

  const { year: sy, month: sm } = s
  const { year: cy, month: cm } = c

  return sy < cy || (sy === cy && sm < cm)
}

/**
 * 判断 select 是否在 current 之后
 * @param {string} select - 格式 "YYYY-M"
 * @param {string} current - 格式 "YYYY-M"
 * @returns {boolean} - 如果 select > current，返回 true
 */
export const isAfterMonth = (select, current) => {
  const parseToYearMonth = (input) => {
    if (!input) return null

    // 支持 Date 实例或可解析的字符串
    if (
      input instanceof Date ||
      !isNaN(Date.parse(input))
    ) {
      const d = new Date(input)
      return {
        year: d.getFullYear(),
        month: d.getMonth() + 1
      }
    }

    // 支持 'YYYY-M' 或 'YYYY-MM' 格式
    const matched = /^(\d{4})-(\d{1,2})$/.exec(input)
    if (matched) {
      return {
        year: Number(matched[1]),
        month: Number(matched[2])
      }
    }

    return null // 无效格式
  }

  const s = parseToYearMonth(select)
  const c = parseToYearMonth(current)

  if (!s || !c) return false

  const { year: sy, month: sm } = s
  const { year: cy, month: cm } = c

  // ✅ 本月及以后都算“之后”
  return sy > cy || (sy === cy && sm >= cm)
}
